<template>
  <div class="aptitude-management">
    <el-dialog
      v-model="visible"
      :title="institutionName"
      width="85%"
      top="5vh"
      class="management-dialog"
    >

      <!-- 主表格 -->
      <div class="table-container">
        <el-table
          :data="manageList"
          border
          stripe
          @sort-change="dataListSortChangeHandle"
          style="width: 100%"
          height="calc(100vh - 280px)"
          v-loading="loading"
          class="aptitude-table"
        >
          <el-table-column
            prop="certificateFilesList"
            label="资质档案"
            sortable="custom"
            header-align="center"
            align="center"
            width="220"
          >
            <template #default="scope">
              <div class="image-list-container">
                <template v-if="scope.row.certificateFilesList?.length">
                  <div class="image-list">
                    <el-image
                      v-for="(img, index) in scope.row.certificateFilesList"
                      :key="index"
                      :src="img"
                      :preview-src-list="getPreviewList(scope.row)"
                      :initial-index="index"
                      fit="contain"
                      :preview-teleported="true"
                      :hide-on-click-modal="true"
                      class="certificate-image"
                    >
                      <template #error>
                        <div class="image-error">
                          <el-icon><Picture /></el-icon>
                          <span>加载失败</span>
                        </div>
                      </template>
                      <template #placeholder>
                        <div class="image-loading">
                          <el-icon :size="20"><Loading /></el-icon>
                        </div>
                      </template>
                    </el-image>
                  </div>
                  <div class="image-count">
                    共 {{ scope.row.certificateFilesList.length }} 张
                  </div>
                </template>
                <span v-else class="no-image">无资质文件</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="qualificationInstructions"
            label="资质说明"
            sortable="custom"
            header-align="center"
            min-width="200"
            show-overflow-tooltip
          >
            <template #default="scope">
              <div class="description-content">
                {{ scope.row.qualificationInstructions || '-' }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="isExamine"
            label="状态"
            sortable="custom"
            header-align="center"
            align="center"
            width="120"
          >
            <template #default="scope">
              <el-tag
                :type="getStatusTagType(scope.row.isExamine)"
                effect="light"
                round
              >
                {{ getStatusText(scope.row.isExamine) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            fixed="right"
            header-align="center"
            align="center"
            width="180"
          >
            <template #default="scope">
              <div class="action-btns">
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row.qualificationId)"
                  :disabled="!checkPermission('sdl:institutionqaq:delete')"
                  plain
                >
                  删除
                </el-button>
                <el-button
                  v-if="scope.row.isExamine === 2"
                  type="primary"
                  size="small"
                  @click="handleEdit(scope.row)"
                  plain
                >
                  编辑
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="dataForm.page"
          v-model:page-size="dataForm.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Picture, Plus, Delete, Loading } from '@element-plus/icons-vue'
import baseService from "@/service/baseService";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  name: "manageAptitude",
  components: {
    Picture,
    Plus,
    Delete,
    Loading
  },
  data() {
    return {
      visible: false,
      loading: false,
      editDialogVisible: false,
      previewVisible: false,
      institutionName: "",
      editTitle: "编辑资质信息",
      currentPreviewImage: '',
      uploadingCount: 0,
      uploadProgress: 0,
      submitting: false,

      rules: {
        qualificationInstructions: [
          { required: true, message: "请输入资质说明", trigger: "blur" },
          { min: 10, message: "资质说明至少需要10个字符", trigger: "blur" }
        ]
      },

      // 分页和数据
      total: 0,
      manageList: [],
      dataForm: {
        page: 1,
        limit: 10,
        order: "",
        orderField: "",
        institutionId: "",
      },

      // 编辑表单
      editForm: {
        qualificationId: "",
        qualificationInstructions: "",
        certificateFilesList: []
      },
      fileList: [],
      editFormRef: null
    };
  },
  methods: {
    // 初始化方法
    init(id, institutionName) {
      this.visible = true;
      this.dataForm.institutionId = id;
      this.institutionName = `${institutionName} - 资质管理`;
      this.getDataList();
    },

    // 获取数据列表
    async getDataList() {
      this.loading = true;
      try {
        const res = await baseService.get("sdl/institutionqaq/manage", this.dataForm);
        if (res.code === 0) {
          this.total = res.data.totalCount;
          this.manageList = res.data.list.map(item => ({
            ...item,
            certificateFilesList: this.normalizeFileList(item.certificateFilesList)
          }));
        }
      } catch (error) {
        ElMessage.error("获取数据失败");
      } finally {
        this.loading = false;
      }
    },

    // 标准化文件列表
    normalizeFileList(fileList) {
      if (!fileList) return [];
      if (Array.isArray(fileList)) return fileList.filter(Boolean);
      return [fileList].filter(Boolean);
    },

    // 获取预览列表
    getPreviewList(row) {
      return row.certificateFilesList || [];
    },

    // 状态相关方法
    getStatusTagType(status) {
      const map = { 0: 'warning', 1: 'success', 2: 'danger' };
      return map[status] || '';
    },

    getStatusText(status) {
      const map = { 0: '待审核', 1: '已通过', 2: '未通过' };
      return map[status] || '';
    },

    // 编辑相关方法
    handleEdit(row) {
      this.editTitle = `编辑资质信息 (ID: ${row.qualificationId})`;
      this.editForm = {
        qualificationId: row.qualificationId,
        qualificationInstructions: row.qualificationInstructions,
        certificateFilesList: this.normalizeFileList(row.certificateFilesList)
      };

      // 初始化文件列表
      this.fileList = this.editForm.certificateFilesList.map((url, index) => ({
        name: `资质文件_${index + 1}`,
        url: url,
        uid: Date.now() + index,
        status: 'success'
      }));

      this.editDialogVisible = true;
    },

    async uploadFiles() {
      this.uploadingCount = 0;
      this.uploadProgress = 0;
      const totalFiles = this.fileList.length;

      if (totalFiles === 0) {
        return true;
      }

      this.uploadingCount = totalFiles;

      try {
        const uploadPromises = this.fileList.map(async (file, index) => {
          if (!file.raw) {
            // 已经是上传过的文件
            this.uploadingCount--;
            return file.url;
          }

          const formdata = new FormData();
          formdata.append("file", file.raw);

          const response = await baseService.post(
            "sdl/institutionqaq/upload/image",
            formdata,
            { "Content-Type": "multipart/form-data" }
          );

          this.uploadingCount--;
          this.uploadProgress = Math.round(((totalFiles - this.uploadingCount) / totalFiles) * 100);

          if (response.code === 0) {
            return response.data;
          } else {
            throw new Error(response.msg || "图片上传失败");
          }
        });

        const results = await Promise.all(uploadPromises);
        this.editForm.certificateFilesList = results.filter(Boolean);
        return true;
      } catch (error) {
        ElMessage.error(error.message || "上传过程中出错");
        return false;
      }
    },

    // 删除记录
    async handleDelete(id) {
      try {
        await ElMessageBox.confirm('确定要删除这条资质记录吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        const res = await baseService.delete(`sdl/institutionqaq/${id}`);
        if (res.code === 0) {
          ElMessage.success('删除成功');
          this.getDataList();
        } else {
          ElMessage.error(res.msg || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除请求失败');
        }
      }
    },

    // 权限检查
    checkPermission(key) {
      return this.$hasPermission(key);
    },

    // 分页相关
    handleSizeChange(val) {
      this.dataForm.limit = val;
      this.getDataList();
    },

    handleCurrentChange(val) {
      this.dataForm.page = val;
      this.getDataList();
    },

    // 排序
    dataListSortChangeHandle(val) {
      this.dataForm.order = val.order === "ascending" ? "asc" :
        val.order === "descending" ? "desc" : "";
      this.dataForm.orderField = this.camelToSnake(val.prop);
      this.getDataList();
    },

    camelToSnake(str) {
      return str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
    }
  }
};
</script>

<style lang="scss" scoped>
.aptitude-management {
  .management-dialog {
    :deep(.el-dialog__header) {
      padding: 16px 24px;
      border-bottom: 1px solid var(--el-border-color-light);
      margin-right: 0;
    }

    :deep(.el-dialog__body) {
      padding: 20px 24px;
    }
  }

  .edit-dialog {
    :deep(.el-dialog__header) {
      padding: 16px 24px;
      border-bottom: 1px solid var(--el-border-color-light);
      margin-right: 0;
    }

    :deep(.el-dialog__body) {
      padding: 20px 24px;
    }

    .form-content {
      padding: 0 12px;
    }

    .upload-item {
      margin-bottom: 24px;

      :deep(.el-form-item__label) {
        padding-bottom: 8px;
        font-weight: 500;
        color: var(--el-text-color-primary);
      }

      .upload-container {
        display: flex;
        gap: 20px;
        align-items: flex-start;
        flex-wrap: wrap;
      }
    }

    .qualification-upload {
      flex: 1;
      min-width: 300px;

      :deep(.el-upload) {
        width: 148px;
        height: 148px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        background-color: var(--el-fill-color-lighter);
        transition: all 0.3s;

        &:hover {
          border-color: var(--el-color-primary);
          background-color: var(--el-color-primary-light-9);
        }
      }

      :deep(.el-upload-list--picture-card) {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin: 0;
      }

      :deep(.el-upload-list__item) {
        width: 148px;
        height: 148px;
        margin: 0;
      }

      .upload-icon {
        font-size: 28px;
        color: var(--el-text-color-secondary);
        margin-bottom: 12px;
      }

      .upload-tip {
        color: var(--el-text-color-regular);
        font-size: 14px;
        text-align: center;
        padding: 0 8px;
      }

      .uploaded-image {
        width: 100%;
        height: 100%;
        position: relative;
        border-radius: 6px;
        overflow: hidden;

        &-el {
          width: 100%;
          height: 100%;
          object-fit: cover;
          cursor: pointer;
        }

        &-actions {
          position: absolute;
          inset: 0;
          display: flex;
          justify-content: center;
          align-items: center;
          background-color: rgba(0, 0, 0, 0.5);
          opacity: 0;
          transition: opacity 0.3s;

          &:hover {
            opacity: 1;
          }
        }

        &-delete {
          color: white;
          font-size: 20px;
          cursor: pointer;
          transition: color 0.2s;

          &:hover {
            color: var(--el-color-danger);
          }
        }
      }
    }

    .upload-hint {
      flex: 0 0 220px;
      padding: 16px;
      background-color: var(--el-fill-color-lighter);
      border-radius: 6px;
      border: 1px solid var(--el-border-color-light);

      .hint-title {
        font-weight: 500;
        margin-bottom: 12px;
        color: var(--el-text-color-primary);
        font-size: 15px;
      }

      .hint-list {
        margin: 0;
        padding-left: 18px;
        color: var(--el-text-color-regular);
        font-size: 13px;
        line-height: 1.8;

        li {
          margin-bottom: 6px;
          position: relative;

          &::before {
            content: "•";
            position: absolute;
            left: -12px;
            color: var(--el-color-primary);
          }
        }
      }

      .upload-progress {
        margin-top: 16px;
        background-color: var(--el-fill-color);
        padding: 8px 12px;
        border-radius: 4px;

        .progress-text {
          font-size: 12px;
          color: var(--el-text-color-secondary);
          margin-bottom: 6px;
        }
      }
    }

    .description-item {
      :deep(.el-form-item__label) {
        padding-bottom: 8px;
        font-weight: 500;
      }

      :deep(.el-textarea__inner) {
        min-height: 120px !important;
        line-height: 1.6;
      }
    }

    .dialog-footer {
      padding: 16px 24px;
      border-top: 1px solid var(--el-border-color-light);
      text-align: right;

      .el-button {
        min-width: 100px;
      }
    }
  }

  /* 表格样式 */
  .table-container {
    margin-bottom: 16px;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

    .aptitude-table {
      :deep(.el-table__cell) {
        padding: 12px 0;
      }

      :deep(th.el-table__cell) {
        background-color: var(--el-fill-color-light);
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      :deep(.el-table__row:hover) {
        background-color: var(--el-fill-color-lighter);
      }
    }
  }

  .image-list-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 8px 0;

    .image-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      justify-content: center;
      margin-bottom: 4px;
      max-width: 100%;
    }

    .certificate-image {
      width: 100px;
      height: 100px;
      border: 1px solid var(--el-border-color);
      border-radius: 4px;
      transition: all 0.3s ease;
      object-fit: contain;
      background-color: var(--el-fill-color-lighter);
      cursor: zoom-in;

      &:hover {
        transform: scale(1.05);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
        border-color: var(--el-color-primary);
      }
    }

    .image-count {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      margin-top: 4px;
    }

    .no-image {
      color: var(--el-text-color-placeholder);
      font-style: italic;
      font-size: 13px;
    }
  }

  .description-content {
    line-height: 1.6;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    color: var(--el-text-color-regular);
    font-size: 14px;
  }

  .action-btns {
    display: flex;
    gap: 8px;
    justify-content: center;

    .el-button {
      min-width: 60px;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding-top: 16px;
    border-top: 1px solid var(--el-border-color-light);
  }

  @media (max-width: 768px) {
    .management-dialog,
    .edit-dialog {
      :deep(.el-dialog) {
        width: 95% !important;
      }
    }

    .upload-container {
      flex-direction: column;
      gap: 16px;
    }

    .upload-hint {
      min-width: 100%;
    }
  }
}
</style>
